package com.kunge2013.service.registry;

import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.api.CuratorWatcher;
import org.apache.curator.framework.api.GetDataBuilder;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author kunge2013
 * @Description 测试zk 接口
 * @Date 2024/10/28 14:15
 * @Version 1.0
 */
@RestController(value = "test")
@Slf4j
public class ZkTestController {
    @Resource
    CuratorFramework zkClient;

    @GetMapping(path = "/get/{service}")
    public Map<String, Object> getConfig(@PathVariable(name = "service") String service) throws Exception {
        return new HashMap<>() {{
            zkClient.getData().usingWatcher(new Watcher() {
                @Override
                public void process(WatchedEvent event) {
                    log.info("getConfig is client event= {}, data = {}", event, event.getType().name());
                }
            });

            put(service + "_data", zkClient.getData().forPath("/" + service));
            put(service + "_Namespace", zkClient.getNamespace());
        }};
    }

    @GetMapping(path = "/update/{key}/{value}")
    public Map<String, Object> update(@PathVariable(name = "key") String key, @PathVariable(name = "value") String value) throws Exception {
        return new HashMap<>() {{
            put(key + "_" + value, zkClient.setData().forPath("/" + key, value.getBytes("UTF-8")));
        }};
    }

    @GetMapping(path = "/watchNode/{nodeId}")
    public Map<String, Object> watchNode(@PathVariable(name = "nodeId") String nodeId) throws Exception {
        return new HashMap<>() {{
            GetDataBuilder data = zkClient.getData();
            CuratorWatcher watcher = new CuratorWatcher() {
                @Override
                public void process(WatchedEvent event) {
                    log.info("processResult is client event= {}, data = {}", event, event.getType().name());
                    try {
                        zkClient.getData().forPath("/" + nodeId);
                        data.usingWatcher(this);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            };
            data.usingWatcher(watcher);
            put(nodeId + "_" + nodeId, data.forPath("/" + nodeId));
        }};
    }


}
